<template>
  <div class="map-container">
    <!-- 地图 -->
    <div id="superviseMap"></div>

    <!-- 地图搜索框 -->
    <div class="search-map-box">
      <el-input id='tipInput' class="search" v-model="searchKeyWord" type="text" placeholder="搜地点"
        :suffix-icon="Search" />
    </div>

    <!-- 地图工具栏1 -->
    <div class="tool-box">
      <div class="tool-item" :class="{ active: satelliteLayerFlag }" @click="satelliteLayer">卫星图</div>
      <div class="tool-item" :class="{ active: rangingToolFlag }" @click="toggleRangingTool">测距</div>
      <div class="tool-item" :class="{ active: mapSelectCarsDatas.mapSelectCarsFlag }" @click="mapSelectCars">地图选车</div>
      <el-dropdown trigger="click" @command="poiCommand">
        <div class="tool-item" :class="{ active: poiSelectFlag }" style="border-right: 1px solid #4E5A75;">POI</div>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="show">显示POI</el-dropdown-item>
            <el-dropdown-item command="close">关闭POI</el-dropdown-item>
            <el-dropdown-item command="edit">
              <el-popover title="POI点添加" placement="bottom" trigger="click" :visible="visible" :width="380">
                <el-form ref="formRef" label-position="right" label-width="100px" :model="poiData.form">
                  <el-col :span="22">
                    <el-form-item label="部门" prop="deptId">
                      <el-tree-select style="width: 100%;" v-model="poiData.form.deptId" :data="deptOptions"
                        :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请选择部门"
                        check-strictly clearable filterable />
                    </el-form-item>
                  </el-col>
                  <el-col :span="22">
                    <el-form-item label="兴趣点名称" prop="names">
                      <el-input v-model="poiData.form.names" placeholder="请输入兴趣点名称" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="22">
                    <el-form-item label="类型" prop="types">
                      <el-select style="width: 100%;" v-model="poiData.form.types">
                        <el-option v-for="dict in safety_label_types" :key="dict.value" :label="dict.label"
                          :value="dict.value"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="22">
                    <el-form-item label="联系人" prop="people">
                      <el-input v-model="poiData.form.people" placeholder="请输入联系人" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="22">
                    <el-form-item label="联系电话" prop="phone">
                      <el-input v-model="poiData.form.phone" placeholder="请输入联系电话" />
                    </el-form-item>
                  </el-col>
                  <el-form-item style="margin-left: 40px;">
                    <el-button :loading="buttonLoading" size="small" type="primary" @click="submitForm">
                      保存
                    </el-button>
                    <el-button size="small" @click="poiClose">关闭</el-button>
                  </el-form-item>
                </el-form>
                <template #reference>
                  <div @click="visible = true">标记POI</div>
                </template>
              </el-popover>
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <div class="tool-item" :class="{ active: trafficLayerFlag }" @click="trafficLayer">路况</div>
      <el-popover placement="bottom" title="选中要显示的电子围栏" :width="550" trigger="click" @show="areaShow">
        <template #reference>
          <div class="tool-item">电子围栏</div>
        </template>
        <Area v-if="areaOpen" />
      </el-popover>
    </div>

    <!-- 地图工具栏2 -->
    <div class="tool2-box">
      <div class="tool-item" @click="draw('close')"><img :src="moveImg" /></div>
      <div class="tool-item" @click="draw('zoomIn')"><img :src="amplifyImg" /></div>
      <div class="tool-item" @click="draw('zoomOut')"><img :src="reduceImg" /></div>
      <div class="tool-item" @click="saveView"><img :src="viewImg" /></div>
    </div>
    <el-dialog :title="mapSelectCarsDatas.title" v-model="mapSelectCarsDatas.open" width="60%" append-to-body
      :before-close="colseSelectCars">
      <selectMapCars v-if="mapSelectCarsDatas.open" :poly-arr="polyArr" />
    </el-dialog>

    <!-- 切换栏表格列表 -->
    <tabsTable />
  </div>
</template>
<script setup>
import tabsTable from '../tabsTable/index.vue'
import moveImg from '@/assets/images/safety/move.png'
import amplifyImg from '@/assets/images/safety/amplify.png'
import reduceImg from '@/assets/images/safety/reduce.png'
import viewImg from '@/assets/images/safety/view.png'
import aiteImg from '@/assets/images/safety/aite.png'
import collectImg from '@/assets/images/safety/collect.png'
import closeImg from '@/assets/images/safety/close.png'
import selectMapCars from './selectMapCars.vue';
import { toDirStr, kmUnit, accStatus } from '@/utils/utils.js'
import Area from './area.vue';
const visible = ref(false)
const buttonLoading = ref(false)
import { Search } from '@element-plus/icons-vue'
import { listLabel } from '@/api/safety/label.js'
import { detaildPageSetting, addPageSetting, updatePageSetting } from '@/api/basic/userPageSetting.js'
import { getPosition } from "@/api/safety/position";
import { addLabel, updateLabel } from '@/api/safety/label.js'
import { ClickOutside as vClickOutside } from 'element-plus'
import useSatetyMapStore from '@/store/modules/safetyMap'
const safeMapStore = useSatetyMapStore();
import { deptTreeSelect } from "@/api/system/user";
const deptOptions = ref([])
const { proxy } = getCurrentInstance();
const { safety_label_types } = proxy.useDict('safety_label_types');
import { initMap } from '@/utils/map'
import { block } from '@antv/x6/lib/registry/marker/classic';
import { computed, watch } from 'vue'

//获取部门下拉树
getDeptTree();
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data;
  });
};

const searchKeyWord = ref('')
const Map = shallowReactive({
  myMap: {}, //把AMap中的方法保存在浏览器
  map: null,
  cluster: null,//聚合
  polygon: [],
  rangingTool: null,
  trafficLayer: null,
  satelliteLayer: null,
  roadNetLayer: null,
  marker: null,
  mouseTool: null,
  areaShape: [], //电子围栏
  allPois: [],//所有兴趣点
  vehicleInfos: [],//车辆数据
  searchMarker: null //地图搜索Poi点
});

//加载地图
newMap();
async function newMap() {
  let plugins = ['AMap.ToolBar', 'AMap.ControlBar', 'AMap.Scale', 'AMap.RangingTool', 'AMap.MouseTool', 'AMap.AutoComplete', 'AMap.PlaceSearch', 'AMap.InfoWindow', 'AMap.PolygonEditor', 'AMap.RectangleEditor', 'AMap.CircleEditor', 'AMap.MarkerCluster'];
  Map.myMap = await initMap(plugins);
  Map.map = new Map.myMap.Map("superviseMap", {
    zoom: 11,
    animateEnable: false
  });
  Map.satelliteLayer = new AMap.TileLayer.Satellite();
  Map.roadNetLayer = new AMap.TileLayer.RoadNet();
  Map.rangingTool = new AMap.RangingTool(Map.map);
  Map.trafficLayer = new AMap.TileLayer.Traffic();
  Map.mouseTool = new AMap.MouseTool(Map.map);
  Map.trafficLayer.setMap(Map.map);
  Map.trafficLayer.hide();

  Map.map.on("complete", function () {
    console.log("地图加载完成！");
    getView();
  });

  var autoOptions = {
    input: "tipInput",	//值为界面上input空间id
    datatype: 'poi'
  }
  var autoCompleteComponent = new AMap.Autocomplete(autoOptions);
  // 注册监听Autocomplete选中项
  autoCompleteComponent.on("select", function (data) {
    console.log(data)
    if (data.poi.location != undefined) {
      //定位到中心点
      Map.map.setCenter(data.poi.location);
      //显示该搜索点
      let searchMarker = new AMap.Marker({
        position: data.poi.location,
        offset: new AMap.Pixel(0, 0),
        anchor: 'bottom-right',
        label: {
          direction: 'right',
          offset: new AMap.Pixel(10, 0),  //设置文本标注偏移量
          content: "<div class='info' style='line-height: 15px'>" + data.poi.name +
            "<div style='font-size:8px; color:red; text-align: right'>右键marker点取消显示</div></div>", //设置文本标注内容
        }
      });
      searchMarker.dom.classList.add('search-poi-info-label')
      Map.map.add(searchMarker)
      //移除该搜索点
      searchMarker.on('rightclick', function () {
        Map.map.remove(searchMarker)
        searchKeyWord.value = ''
      })
    }
  })

  //绑定地图移动与缩放事件
  Map.map.on('moveend', logMapinfo);
  Map.map.on('zoomend', logMapinfo);
}

//获取地图视野参数以及设置
var mapPageKey = 'mapSet';
const mapConfig = ref(null);
function getView() {
  detaildPageSetting(mapPageKey).then(res => {
    if (res.data != null) {
      res.data.content = JSON.parse(res.data.content);
      mapConfig.value = res.data
      Map.map.setZoomAndCenter(mapConfig.value.content.zoom, mapConfig.value.content.center);
    }
  })
}

//返回地图车辆marker的信息窗体按钮选中类型
const ibtFlag = computed(() => {
  return safeMapStore.mapInfowWindowBtFlag;
})

//返回选中tab类别
const carEjectFlag = computed(() => {
  return safeMapStore.mapCarEjectFlag
});

//监听选中tab类别
watch(carEjectFlag, (newValue) => {
  if (newValue == 'roll' || newValue == 'voice') {
    safeMapStore.setMapInfowWindowBtFlag(newValue)
  }
  showCarInfo()
})

//获取地图当前级别和中心位置
function logMapinfo() {
  var zoom = Map.map.getZoom(); //获取当前地图级别
  var center = Map.map.getCenter(); //获取当前地图中心位置
  console.log('当前地图信息：', zoom, center.toString())
};

//构建自定义信息窗体
function createInfoWindow(item = {}) {
  console.log('当前车辆信息', item)
  // console.log('111', ibtFlag.value)
  var info = document.createElement("div");
  info.className = "custom-info input-card content-window-card";

  //可以通过下面的方式修改自定义窗体的宽高
  // 定义顶部标题
  var top = document.createElement("div");
  var titleD = document.createElement("div");
  var imgBox = document.createElement("div");
  imgBox.className = 'map-img-box'
  var aiteBtn = document.createElement("img");
  aiteBtn.className = 'aite-img'
  aiteBtn.src = aiteImg
  var collectBtn = document.createElement("img");
  collectBtn.className = 'collect-img'
  collectBtn.src = collectImg
  var closeX = document.createElement("img");
  top.className = "info-top";
  titleD.innerHTML = `${item.plateNo} (${item.numbered})`;
  closeX.src = closeImg;
  closeX.onclick = closeInfoWindow;
  imgBox.appendChild(aiteBtn)
  imgBox.appendChild(collectBtn)
  imgBox.appendChild(closeX)
  top.appendChild(titleD);
  top.appendChild(imgBox);
  info.appendChild(top);

  // 定义中部内容
  var middle = document.createElement("div");
  middle.className = "info-middle";
  middle.style.backgroundColor = '#16254A';
  middle.innerHTML = `
  <div class="speed-box">
    <div class="speed-img">
      <div class="speed">${item.speed ? item.speed : 0}</div>
      <div>km/h</div>
    </div>
    <div class="car-info-box">
      <div class="car-row">
        <div class="car-info">
          <div class="info-label">驾驶员</div>
          <div class="info-font">${item.driverName}</div>
        </div>
        <div class="car-info">
          <div class="info-label">所属机构</div>
          <div class="info-font">${item.deptName}</div>
        </div>
      </div>
      <div class="car-row">
        <div class="car-info">
          <div class="info-label">今日里程</div>
          <div class="info-font">${kmUnit(item.todayMileage)}KM</div>
        </div>
        <div class="car-info">
          <div class="info-label">总里程</div>
          <div class="info-font">${kmUnit(item.mileage)}KM</div>
        </div>
      </div>
      <div class="car-row">
        <div class="car-info">
          <div class="info-label">海拔</div>
          <div class="info-font">${item.height || 0}m</div>
        </div>
        <div class="car-info">
          <div class="info-label">定位时间</div>
          <div class="info-font">${item.gpsTime}</div>
        </div>
      </div>
      <div class="car-row">
        <div class="car-info">
          <div class="info-label">点火状态</div>
          <div class="info-font">${accStatus(item.state)}</div>
        </div>
        <div class="car-info">
          <div class="info-label">回传时间</div>
          <div class="info-font">${item.onlineTime}</div>
        </div>
      </div>
      <div class="car-row">
        <div class="car-info">
          <div class="info-label">设备号</div>
          <div class="info-font">${item.deviceCode}</div>
        </div>
        <div class="car-info">
          <div class="info-label">SIM号</div>
          <div class="info-font">${item.msisdn}</div>
        </div>
      </div>
    </div>
  </div>
  <div class="line-row car-row">
      <div class="car-info2 speed-limit">
        <div class="info-label">限速值</div>
        <div class="info-font">${item.limitSpeed}KM/H</div>
      </div>
      <div class="speed-other">
        <div class="car-info2" style="width: 140px">
          <div class="info-label">方向</div>
          <div class="info-font">${toDirStr(item.direction)}</div>
        </div>
        <div class="car-info2" style="margin-right:30px">
          <div class="info-label">卫星数</div>
          <div class="info-font">${item.satelliteCount}</div>
        </div>
        <div class="car-info2">
          <div class="info-label">网络信号</div>
          <div class="info-font">${item.signalStrength}</div>
        </div>
      </div>
  </div>
  <div class="line-row car-row">
      <div class="car-info2">
        <div class="info-label">报警</div>
        <div class="info-font" style="color:red">${item.alarm}</div>
      </div>
  </div>
  <div class="line-row car-row">
      <div class="car-info2">
        <div class="info-label">所在位置</div>
        <div class="info-font" style="width:450px">${item.location}</div>
      </div>
  </div>
  `;
  info.appendChild(middle);
  var bottom = document.createElement("div");
  bottom.className = "info-bottom";
  bottom.innerHTML = `<div>
    <div class="info-bottom-btn ${carEjectFlag.value == 'roll' && ibtFlag.value == 'roll' ? 'ibt-active' : ''}" onclick="carInfoWindowBtClick('roll')">点名</div>
    <div class="info-bottom-btn ${carEjectFlag.value == 'status' && ibtFlag.value == 'liveVideo' ? 'ibt-active' : ''}" onclick="carInfoWindowBtClick('liveVideo')">实时视频</div>
    <div class="info-bottom-btn" onclick="carInfoWindowBtClick('playback')">视频回放</div>
    <div class="info-bottom-btn" onclick="carInfoWindowBtClick('pathback')">轨迹回放</div>
    </div>
    <div>
    <img src="/safety/img/voice.png" />
    <img src="/safety/img/send_msg.png" />
    <img src="/safety/img/take_photo.png" />
    <img src="/safety/img/lists.png" />
    <img src="/safety/img/setting1.png" />
    </div>`
  info.appendChild(bottom)
  return info;

}

//关闭信息窗体并清除当前选中的车辆ID
window.closeInfoWindow = function () {
  Map.map.clearInfoWindow();
}

//卫星图
const satelliteLayerFlag = ref(false);
function satelliteLayer() {
  // 构造官方卫星、路网图层
  if (satelliteLayerFlag.value) {
    Map.map.remove([Map.satelliteLayer, Map.roadNetLayer]);
    satelliteLayerFlag.value = false;
  } else {
    Map.map.add([Map.satelliteLayer, Map.roadNetLayer]);
    satelliteLayerFlag.value = true;
  }
}

//测距方法
const rangingToolFlag = ref(false)
function toggleRangingTool() {
  rangingToolFlag.value = !rangingToolFlag.value;
  if (rangingToolFlag.value) {
    Map.rangingTool.turnOn();

    Map.rangingTool.on('end', function (e) {
      Map.rangingTool.turnOff();
      rangingToolFlag.value = false;
    })
  } else {
    Map.rangingTool.turnOff(true)
  }

  //关闭地图选车功能
  mapSelectCarsDatas.mapSelectCarsFlag = false
  Map.mouseTool.close(true);
}

//实时路况图层 
const trafficLayerFlag = ref(false);
function trafficLayer() {
  if (trafficLayerFlag.value) {
    Map.trafficLayer.hide();
    trafficLayerFlag.value = false;
  } else {
    Map.trafficLayer.show();
    trafficLayerFlag.value = true;
  }
}

//地图选车
const polyArr = ref([])
const mapSelectCarsDatas = reactive({
  mapSelectCarsFlag: false,
  title: '地图选车',
  open: false
})
function mapSelectCars() {
  mapSelectCarsDatas.mapSelectCarsFlag = !mapSelectCarsDatas.mapSelectCarsFlag;
  Map.mouseTool.close(true);

  if (mapSelectCarsDatas.mapSelectCarsFlag) {
    //打开地图矩形绘制
    Map.mouseTool = new AMap.MouseTool(Map.map);
    draw('rectangle')

    //根据绘制的矩形地图选车
    Map.mouseTool.on('draw', function (event) {
      let point = [];
      let polys = event.obj.getPath()
      polys.forEach((item) => {
        point.push({ longitude: item.lng, latitude: item.lat })
      })
      polyArr.value = point
      mapSelectCarsDatas.open = true
    })

    //关闭测距功能
    closeRingingTool()
  }
}

//关闭测距
function closeRingingTool() {
  rangingToolFlag.value = false;
  Map.rangingTool.turnOff(true);
}

//关闭地图选车
function colseSelectCars() {
  mapSelectCarsDatas.open = false
  mapSelectCarsDatas.mapSelectCarsFlag = false
  Map.mouseTool.close(true);
}

// poi操作
const poiData = reactive({
  form: {
    lat: null,
    lon: null,
    name: null,
    type: '1',
    contact: null,
    phone: null,
  },
  marker: null,
})
const poiSelectFlag = ref(false)
function poiReset() {
  Map.map.clearEvents('click');

  poiData.marker = poiData.marker ? Map.map.remove(poiData.marker) : null;
  poiData.form = {
    id: null,
    lat: null,
    lon: null,
    name: null,
    deptId: deptOptions.value[0].id,
    types: '1',
    people: null,
    phone: null,
  }
}
//poi Command操作
function poiCommand(command) {
  if (command == 'show') {
    poiSelectFlag.value = true;
    safeMapStore.setPoiTabShow(true);
  }
  if (command == 'close') {
    poiSelectFlag.value = false;
    safeMapStore.setPoiTabShow(false);
    safeMapStore.setAllPois([])
  }
  if (command == 'edit') {
    poiReset();

    Map.map.on('click', function (e) {
      poiData.marker = poiData.marker ? Map.map.remove(poiData.marker) : null;
      poiData.marker = new AMap.Marker({
        position: [e.lnglat.getLng(), e.lnglat.getLat()],
        draggable: true,
      });
      poiData.marker.setMap(Map.map);
      poiData.form.lon = e.lnglat.getLng()
      poiData.form.lat = e.lnglat.getLat()

      poiData.marker.on('dragend', function (e) {
        let position = e.target.getPosition()
        poiData.form.lon = position.lng
        poiData.form.lat = position.lat
      })
    });
  }
}
function poiClose() {
  visible.value = false;
  poiReset();
}
function getPoiList() {
  listLabel().then(response => {
    poiReset();
    safeMapStore.setAllPois(JSON.parse(JSON.stringify(response.data)))
  });
}
//POI新增
function submitForm() {
  proxy.$refs["formRef"].validate(valid => {
    if (poiData.form.lon == null || poiData.form.lat == null) {
      proxy.$modal.msgError("请先标记POI点");
      return false;
    }

    if (valid) {
      buttonLoading.value = true;
      if (poiData.form.id == null) {
        addLabel(poiData.form).then(res => {
          proxy.$modal.msgSuccess("保存成功");
          visible.value = false
          Map.map.clearEvents('click');
          getPoiList()
        }).finally(() => {
          buttonLoading.value = false;
        });
      }
    }
  });
}

//电子围栏
const areaOpen = ref(false)
function areaShow() {
  areaOpen.value = true
  draw('close')
}

//返回vueX仓库的选中的电子围栏数据
const selectAreas = computed(() => {
  return safeMapStore.selectAreas
})

//监听电子围栏数据是否改变
watch(selectAreas, (newValue, oldValue) => {
  console.log('selectAreas', newValue, oldValue)
  if (Map.areaShape.length > 0) {
    Map.map.remove(Map.areaShape);
    Map.areaShape = [];
  }
  newValue.map(item => {
    let vo = JSON.parse(JSON.stringify(item))
    vo.lonlat = _buildAreaLnglat(vo)
    // 0圆形，1矩形，2多边形
    if (vo.shape == 0) {
      console.log(vo)
      var circle = new AMap.Circle({
        center: [vo.lonlat[0], vo.lonlat[1]],
        radius: vo.lonlat[2] //半径
      })
      Map.areaShape.push(circle)
    }
    if (vo.shape == 1) {
      var southWest = new AMap.LngLat(vo.lonlat[0][0], vo.lonlat[0][1])
      var northEast = new AMap.LngLat(vo.lonlat[1][0], vo.lonlat[1][1])
      var bounds = new AMap.Bounds(southWest, northEast)
      var rectangle = new AMap.Rectangle({
        bounds: bounds
      })
      Map.areaShape.push(rectangle)
    }
    if (vo.shape == 2) {
      console.log(vo.lonlat);
      let polygon = new AMap.Polygon({
        path: vo.lonlat
      })
      Map.areaShape.push(polygon)
    }

  })
  Map.map.add(Map.areaShape);
  Map.map.setFitView()
}, { deep: true })
function _buildAreaLnglat(item) {
  let lonlats = item.lonlat.split(',')
  let returnLonlats = [];
  let loglat = [];
  // 0圆形，1矩形，2多边形
  if (item.shape == 0) {
    returnLonlats = lonlats;
  }
  if (item.shape == 1 || item.shape == 2) {
    lonlats.forEach((vo, index) => {
      loglat.push(vo)
      if (index % 2 == 1) {
        returnLonlats.push(loglat);
        loglat = [];
      }
    })
  }
  return returnLonlats;
}

//地图鼠标工具
function draw(type) {
  switch (type) {
    case 'close': {
      Map.mouseTool.close(true);
      Map.map.setStatus({ dragEnable: true })// 开启鼠标平移功能
      closeRingingTool()
      colseSelectCars()
      break;
    }
    case 'zoomIn': {
      closeRingingTool()
      colseSelectCars()
      Map.mouseTool.rectZoomIn({
        strokeColor: '#80d8ff',
        fillColor: '#80d8ff',
        fillOpacity: 0.3
        //同 Polygon 的 Option 设置
      });
      break;
    }
    case 'zoomOut': {
      closeRingingTool()
      colseSelectCars()
      Map.mouseTool.rectZoomOut({
        strokeColor: '#80d8ff',
        fillColor: '#80d8ff',
        fillOpacity: 0.3
        //同 Polygon 的 Option 设置
      });
      break;
    }
    case 'rectangle': {
      Map.mouseTool.rectangle({
        strokeColor: '#11224B',
        strokeOpacity: 0.5,
        strokeWeight: 2,
        fillColor: '#668FF5',
        fillOpacity: 0.5,
        strokeStyle: 'solid',
      });
      break;
    }
  }
}

//保存地图视野
function saveView() {
  let data = {
    'zoom': Map.map.getZoom(), //获取当前地图级别
    'center': Map.map.getCenter(), //获取当前地图中心位置
  }
  let parmas = {
    page: mapPageKey,
    content: JSON.stringify(data)
  }
  if (mapConfig.value == null) {
    addPageSetting(parmas).then(res => {
      proxy.$modal.msgSuccess("保存成功");
    })
  } else {
    parmas.id = mapConfig.value.id;
    updatePageSetting(parmas).then(res => {
      proxy.$modal.msgSuccess("保存成功");
    })
  }
}

//返回vueX仓库的Poi点数据
const allPois = computed(() => {
  return safeMapStore.allPois
})

//监听兴趣点，显示兴趣点
watch(allPois, (newValue) => {
  console.log('allPois', new Date(), newValue)
  // if (newValue.length > 0) {
  Map.map.remove(Map.allPois)
  Map.allPois = [];
  // }
  newValue.forEach(item => {
    let marker = new AMap.Marker({
      position: [item.lon, item.lat],
      offset: new AMap.Pixel(0, 0),
      anchor: 'bottom-right',
      label: {
        direction: 'right',
        offset: new AMap.Pixel(10, 0),  //设置文本标注偏移量
        content: "<div class='info'>" + item.names + "</div>", //设置文本标注内容
      }
    });
    marker.dom.classList.add('poi-info-label')
    Map.allPois.push(marker)
  })
  Map.map.add(Map.allPois)
}, { deep: true })

//返回vueX仓库的当前选中的车辆ID
const currentSelectVehicleId = computed(() => {
  return [safeMapStore.currentSelectVehicleId, safeMapStore.opTime]
})

//返回vueX仓库的当前选中的车辆数据
const currentSelectVehicleData = computed(() => {
  return safeMapStore.currentSelectVehicleData
})

//显示车辆信息窗体
function showCarInfo() {
  let item = currentSelectVehicleData.value
  // console.log('currData', item)
  if (item) {
    let content = createInfoWindow(item)
    _showMapInfoWindow(content, [item.longitude, item.latitude])
  }
}

function _showMapInfoWindow(content = '', center = []) {
  var infoWindow = new AMap.InfoWindow({ isCustom: true, offset: new AMap.Pixel(16, -45) });
  infoWindow.setContent(content);
  infoWindow.open(Map.map, center);
  Map.map.setZoom(13, true, 0)
  Map.map.setCenter(center)
}

//监听当前选中的车辆ID和数据
watch([currentSelectVehicleId, currentSelectVehicleData], (newValue, oldValue) => {
  if (newValue[0][0] != '') {
    showCarInfo()
  } else {
    Map.map == null ? '' : Map.map.clearInfoWindow();
  }
})

//返回vueX仓库的地图中心点
const mapCenterLngLat = computed(() => {
  return safeMapStore.mapCenterLngLat
})

//监听地图中心点
watch(mapCenterLngLat, (newValue) => {
  Map.map.setCenter(newValue)
})

//返回vueX仓库的选中的车辆数据
const selectedVehicleDatas = computed(() => {
  return safeMapStore.selectedVehicleDatas
})

//聚合绘画
function createPlateNosWindow(items = []) {
  let plateBox = document.createElement("div");
  plateBox.className = "maptalks-menu";
  plateBox.style = 'width: 160px; background-color:#FFF';
  var ul = document.createElement("ul");
  ul.className = 'maptalks-menu-items'
  // console.log('items', items[0]._amapMarker.originData)
  items.forEach(vos => {
    vos._amapMarker.originData[0].forEach((item) => {
      var li = document.createElement("li");
      li.innerHTML = item.plateNo;
      li.onclick = function () {
        safeMapStore.setCurrentSelectVehicleId(item.vehicleId)
        showCarInfo()
      };
      ul.appendChild(li)
    })

  })
  plateBox.appendChild(ul)
  return plateBox;
}

var pointCount = 0;
//绘画聚合点
function _renderClusterMarker(context) {
  // 聚合中点个数
  var clusterCount = context.count;
  var div = document.createElement('div');
  // 聚合点配色
  var bgColor = '8,60,156';
  div.style.backgroundColor = 'rgba(' + bgColor + ',.8)';
  var size = Math.round(25 + Math.pow(clusterCount / pointCount, 1 / 5) * 40);
  div.style.width = div.style.height = size + 'px';
  div.style.border = 'solid 1px rgba(' + bgColor + ',1)';
  div.style.borderRadius = size / 2 + 'px';
  div.innerHTML = context.count;
  div.style.lineHeight = size + 'px';
  div.style.color = '#ffffff';
  div.style.fontSize = '12px';
  div.style.textAlign = 'center';
  context.marker.setOffset(new AMap.Pixel(-size / 2, -size / 2));
  context.marker.setContent(div);
  context.marker.on('click', function (e) {
    let infoWindow = new AMap.InfoWindow({
      isCustom: true,  //使用自定义窗体
      closeWhenClickMap: true,
      content: createPlateNosWindow(context.clusterData),
      anchor: 'bottom-right',
      offset: new AMap.Pixel(16, -45)
    });
    infoWindow.open(Map.map, context.marker.getPosition());
    // Map.map.setZoomAndCenter(16, context.marker.getPosition());
  });
}
//车辆maker点绘画
var _renderMarker = function (context) {
  let item = context.data[0];
  // console.log('item', item)
  context.marker.content = createInfoWindow(item)
  context.marker.setIcon('/safety/img/' + item.vehicleStatus + '_big_car.png')
  context.marker.setLabel({
    content: item.plateNo,
    direction: 'bottom-center',
    offset: new AMap.Pixel(0, 10)
  })
  context.marker.dom.classList.add('plate-info-label')
  context.marker.dom.getElementsByClassName('amap-icon')[0].style.transform = `rotate(${item.direction + 90}deg)`
  context.marker.setExtData(item)

  let markerClick = function (e) {
    _showMapInfoWindow(e.target.content, e.target.getPosition())
    //点击车辆marker点后设置选中当前车辆Id
    let extData = e.target.getExtData()
    safeMapStore.setCurrentSelectVehicleId(extData.vehicleId)
  }
  context.marker.on('click', markerClick);
}

//监听选中的车辆数据
watch(selectedVehicleDatas, (newValue, oldValue) => {
  // console.log('监听选中的车辆数据', newValue, oldValue)
  if (Map.vehicleInfos.length > 0) {
    Map.map.remove(Map.vehicleInfos)
  }
  if (Map.cluster) {
    Map.cluster.setMap(null);
  }
  var points = JSON.parse(JSON.stringify(newValue))
  pointCount = points.length;
  if (pointCount == 0 || pointCount == undefined) {
    return false;
  } else {
    points.forEach((item) => {
      item.lnglat = [item.longitude, item.latitude]
    })
    Map.cluster = new AMap.MarkerCluster(Map.map, points, {
      gridSize: 80,
      renderClusterMarker: _renderClusterMarker,
      renderMarker: _renderMarker,
    })
  }
}, { deep: true })


//地图车辆marker信息窗体内的按钮点击事件
window.carInfoWindowBtClick = function (e) {
  if (e == 'roll') { //点击点名操作
    safeMapStore.setMapCarEjectFlag(e) //切换车辆信息框选中项
    changeTreeHeight(259) //展示车辆信息框

  } else if (e == 'liveVideo') {
    safeMapStore.setMapCarEjectFlag('status')
    safeMapStore.setMapVideoListWidth(290)
  }

  safeMapStore.setMapInfowWindowBtFlag(e) //切换信息窗体内的按钮 让其成选中状态
  showCarInfo() //重新渲染车辆信息窗体
}

//显示隐藏车辆信息状态框
function changeTreeHeight(e) {
  safeMapStore.setTreeEjectHeight(e)
  safeMapStore.setZtreeHeight(e == 259 ? 480 : 707)
}

</script>

<style lang="scss" scoped>
.map-container {
  flex: 1;
  width: 100%;
  // height: 100%;
  position: relative;
  display: flex;
  flex-direction: column;

  .tool-box {
    position: absolute;
    right: 20px;
    top: 6px;
    display: flex;
    background-color: #1C2F61;
    border: 1px solid #4E5A75;
    border-radius: 5px;

    .tool-item {
      padding: 7px 9px;
      font-size: 12px;
      line-height: 12px;
      color: #9BAFD6;
      border-right: 1px solid #4E5A75;
      cursor: pointer;

      &:last-child {
        border-right: 0;
      }

      &.active {
        background-color: #5072C9;
        color: #FFFFFF;
      }
    }
  }

  .tool2-box {
    position: absolute;
    right: 20px;
    top: 50px;
    display: flex;
    flex-direction: column;

    .tool-item {
      width: 27px;
      height: 27px;
      background-color: #1C2F61;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 4px;
      cursor: pointer;
      border-radius: 5px;
    }
  }

  .search-map-box {
    position: absolute;
    right: 400px;
    top: 6px;

    .search {
      width: 136px;

      & :deep(.el-input__wrapper) {
        background-color: #1C2F61;
        color: #9BAFD6;
        padding: 0 10px;
      }

      & :deep(.el-input__inner) {
        color: #9BAFD6;
        font-size: 12px;
      }
    }
  }


  #superviseMap {
    width: 100%;
    height: 100%;
  }

  #superviseMap :deep(.plate-info-label .amap-marker-label) {
    border: 0;
    padding: 5px;
    border-radius: 5px;
    background-color: #668FF5;
    color: white;
    width: auto;
    box-shadow: 0 2px 6px 0 white;
  }

  #superviseMap :deep(.search-poi-info-label .amap-marker-label),
  #superviseMap :deep(.poi-info-label .amap-marker-label) {
    padding: 5px;
    border-radius: 5px;
    background-color: white;
    border-width: 0;
    box-shadow: 0 2px 6px 0 rgba(114, 124, 245, .5);
  }
}
</style>

<style lang="scss">
.amap-logo {
  top: 0px;
}

.amap-copyright {
  top: 0px;
  display: none !important;
}

.content-window-card {
  // width: 632px;
  // height: 308px;
  width: 520px;
  // height: 308px;
  background-color: #16254A;
  box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.2);
  opacity: 0.95;
  border-radius: 10px;

  img {
    cursor: pointer;
  }
}


div.info-top {
  color: #FFFFFF;
  padding-left: 25px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 40px;
  border-bottom: 1px solid #4E5A75;
}

.info-top .map-img-box {
  display: flex;
  align-items: center;
  margin-right: 16px;
}

div.info-top .collect-img {
  margin: 0 24px 0 10px;
}

div.info-middle {
  font-size: 12px;
  padding: 10px;
  line-height: 12px;
}

.speed-box {
  display: flex;
}

.speed-box .speed-img {
  width: 135px;
  height: 68px;
  background-image: url('@/assets/images/safety/speedometer.png');
  color: #1CCFEB;
  display: flex;
  flex-direction: column;
  font-size: 18px;
  justify-content: end;
  align-items: center;
  margin-right: 10px;
}

.speed-img .speed {
  margin-bottom: 5px;
  font-size: 22px;
}

.speed-box .car-info-box {
  display: flex;
  flex-direction: column;
  width: calc(100% - 148px);
}

.car-info-box .car-row,
.car-info-box .car-info {
  display: flex;
}

.car-info-box .car-info:first-child {
  width: 40%;
  padding: 5px 0;
}

.car-info-box .car-info:last-child {
  width: 60%;
  padding: 5px 0;
}

.car-row .info-label {
  color: #9BAFD6;
  width: 55px;
  text-align: left;
}

.car-row .info-font {
  flex: 1;
  color: #FFFFFF;
}

.line-row.car-row,
.line-row .car-info2 {
  display: flex;
}

.car-info2 {
  padding: 5px 0;
}

.speed-limit {
  width: 205px;
}

.speed-other {
  display: flex;
  width: 100%;
}

div.info-bottom {
  border-top: 1px solid #4E5A75;
  border-radius: 0px 0px 10px 10px;
  display: flex;
  justify-content: space-between;
  padding: 10px 20px;
  background-color: #1C2F61;
}

div.info-bottom div {
  display: flex;
  align-items: center;
  justify-content: center;
}

div.info-bottom div .info-bottom-btn {
  width: 60px;
  height: 26px;
  border: 1px solid #668FF5;
  border-radius: 2px;
  line-height: 26px;
  font-size: 12px;
  color: #668FF5;
  text-align: center;
  margin-right: 8px;
}

div.info-bottom div .info-bottom-btn:hover,
div.info-bottom div .info-bottom-btn.ibt-active {
  color: #FFF;
  background: #668FF5;
}

div.info-bottom div img {
  margin-right: 15px;
}

div.info-bottom div img:last-child {
  margin-right: 0px;
}

.maptalks-menu .maptalks-menu-items {
  color: #5a5756;
  margin: 0;
  padding: 0;
  font-size: 12px;
  max-height: 200px;
  overflow-y: scroll;
}

.maptalks-menu .maptalks-menu-items li {
  list-style: none;
  height: 30px;
  line-height: 30px;
  text-indent: 16px
}

.maptalks-menu .maptalks-menu-items li:hover {
  background: #007fbe;
  color: #fff;
  cursor: pointer
}
</style>